Add useAppState() hook for tracking app foreground/background state#56386
Add useAppState() hook for tracking app foreground/background state#56386Nedunchezhiyan-M wants to merge 1 commit intofacebook:mainfrom
Conversation
Add a new React hook that lets components subscribe to app state
changes using the modern useSyncExternalStore pattern, matching
the existing useColorScheme and useWindowDimensions hooks.
This solves a common pain point where developers must manually
manage AppState event listeners and local state to know if the
app is in foreground or background. Common use cases include:
- Refreshing data when the app returns to foreground
- Pausing media playback when backgrounded
- Saving drafts when the user leaves
- Disabling timers in background
Usage:
import { useAppState } from 'react-native';
function MyComponent() {
const appState = useAppState();
// Returns: 'active' | 'background' | 'inactive' | 'unknown'
}
|
Thank you for your pull request and welcome to our community. Action RequiredIn order to merge any pull request (code, docs, etc.), we require contributors to sign our Contributor License Agreement, and we don't seem to have one on file for you. ProcessIn order for us to review and merge your suggested changes, please sign at https://code.facebook.com/cla. If you are contributing on behalf of someone else (eg your employer), the individual CLA may not be sufficient and your employer may need to sign the corporate CLA. Once the CLA is signed, our tooling will perform checks and validations. Afterwards, the pull request will be tagged with If you have received this in error or have any questions, please contact us at cla@meta.com. Thanks! |
04e42aa to
27c4fdf
Compare
|
Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks! |
Summary
Add a new
useAppState()React hook that lets components subscribe to app state changes, following the same pattern as the existinguseColorScheme()anduseWindowDimensions()hooks.Problem
Currently, tracking app state requires manually managing AppState event listeners and local state:
Solution
A single-line hook using React's
useSyncExternalStore:Common use cases for mobile apps
What's included
useAppState.js- Hook implementation usinguseSyncExternalStoreuseAppState.d.ts- TypeScript declarationsreact-nativepackage (index.js + index.js.flow)useAppStatereturns'active'by default)useColorSchemetest patternChangelog:
[GENERAL] [ADDED] - Add useAppState() hook for subscribing to app foreground/background state changes
Test Plan
useAppStatefromreact-nativeand use in a component'active'when the app is in the foreground'background''active''inactive'state